var $P = {
    supplementFullDate: function (obj, keys, format) {
        if (format == undefined) {
            format = "yyyy-MM-dd";
        }
        if (format == "yyyy-MM-dd") {
            for (var i = 0; i < keys.length; i++) {
                if (!$P.isnullorempty(obj[keys[i]])) {
                    obj[keys[i]] += " 00:00:00";
                }
            }
        }
        return obj;
    },
    trimJson: function (obj) {
        for (var key in obj) {
            if ((typeof obj[key]) == "string") {
                obj[key] = obj[key].trim();
            }
        }
        return obj;
    },

    cloneObj: function (data) {
        var obj = {};
        var originQueue = [data];
        var copyQueue = [obj];
        //以下两个队列用来保存复制过程中访问过的对象，以此来避免对象环的问题（对象的某个属性值是对象本身）
        var visitQueue = [];
        var copyVisitQueue = [];
        while (originQueue.length > 0) {
            var _data = originQueue.shift();
            var _obj = copyQueue.shift();
            visitQueue.push(_data);
            copyVisitQueue.push(_obj);
            for (var key in _data) {
                var _value = _data[key]
                if (typeof _value !== 'object') {
                    _obj[key] = _value;
                } else {
                    //使用indexOf可以发现数组中是否存在相同的对象(实现indexOf的难点就在于对象比较)
                    var index = visitQueue.indexOf(_value);
                    if (index >= 0) {
                        _obj[key] = copyVisitQueue[index];
                    }
                    originQueue.push(_value);
                    copyQueue.push(_obj[key]);
                }
            }
        }
        return obj;
    },

    uuidgen: function () {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("");
        return uuid;
    },

    /*获取时间触发控件*/
    getElFromEvent: function (event) {
        return $(event.target);
    },
    /*验证字符是否为空*/
    isnullorempty: function (arg) {
        if ((typeof arg) == 'number' && !isNaN(arg)) return false;
        if ((typeof arg) == 'boolean') return false;
        return arg == undefined || arg == '' || arg == 'null' || arg == null;
    },
    /*获取默认值*/
    gv: function (arg, def) {
        if (this.isnullorempty(arg))
            return def || def == 0 ? def : '';
        else {
            if ((typeof arg) == 'string')
                return arg.trim();
            else
                return arg;
        }
    },
    //获取有效的el
    gel: function () {
        for (var i = 0; i < arguments.length; i++) {
            if (arguments[i] !== undefined && (arguments[i].length == undefined || arguments[i].length > 0)) {
                return arguments[i];
            }
        }
        return undefined;
    },
    /*根据传入的条件判断是否和合法的数字*/
    isnumber: function (value, dot, min, max) {
        var ret = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
        if (ret && (typeof dot) == 'number' && dot >= 0) {
            if (dot == 0) {
                ret = /^-?\d+$/.test(value);
            } else {
                eval("var rg = /^-?\\d+(\\.\\d{1," + dot + "})?$/;");
                ret = rg.test(value);
            }
        }

        var bminself = true;
        var bmaxself = true;
        if (ret && (typeof min) == 'string') {
            min = parseFloat(min);
            bminself = false;
        }
        if (ret && (typeof max) == 'string') {
            max = parseFloat(max);
            bmaxself = false;
        }

        if (ret && (typeof min) == 'number') {
            if (bminself)
                ret = parseFloat(value) >= min;
            else
                ret = parseFloat(value) > min;
        }

        if (ret && (typeof max) == 'number') {
            if (bmaxself)
                ret = parseFloat(value) <= max;
            else
                ret = parseFloat(value) < max;
        }
        return ret;
    },
    /*根据后台返回的实体验证规初始化表单验证规则*/
    initFormRule: function (formEl, beanName, group) {
        app.callAjaxPost('../../../../api/ValidController/getRules', {
            beanName: beanName,
            group: group
        }, function (result) {
            if (result.success == true) {
                $P.doFormRule(formEl, result.data);
            }
        });
    },
    /*根据后台返回的实体验证规初始化表单元素验证规则*/
    doFormRule: function (formEl, data) {
        if (formEl == undefined || data == null || data == undefined) {
            return;
        }
        for (var key in data) {
            $P.doFormElmentRule(formEl, key, data[key]);
        }
    },
    /**获取几位整数*/
    getNumber: function (lop) {
        var num = 1;
        lop = lop * 1;
        for (var i = 0; i < lop; i++) {
            num = num * 10
        }
        return num;
    },
    /**设置表单元素验证规则**/
    doFormElmentRule: function (formEl, elementId, ruleArray) {
        try {
            var el = $P.gel(formEl.find("#" + elementId), formEl.find("[name=" + elementId + "]"), formEl.find("[vid=" + elementId + "]"));

            if (el == undefined || el.length == 0) {
                return false;
            }

            for (var i = 0; i < ruleArray.length; i++) {
                var rule = ruleArray[i];
                if (rule["rule"] == "notnull") {
                    el.attr("required", true);
                    if (!$P.isnullorempty(rule["message"])) {
                        el.attr("required_msg", rule["message"]);
                    }
                } else if (rule["rule"] == "notblank") {
                    el.attr("required", true);
                    if (!$P.isnullorempty(rule["message"])) {
                        el.attr("required_msg", rule["message"]);
                    }
                } else if (rule["rule"] == "notempty") {
                    el.attr("required", true);
                    if (!$P.isnullorempty(rule["message"])) {
                        el.attr("required_msg", rule["message"]);
                    }
                } else if (rule["rule"] == "email") {
                    el.attr("email", true);
                    if (!$P.isnullorempty(rule["message"])) {
                        el.attr("email_msg", rule["message"]);
                    }
                } else if (rule["rule"] == "min") {
                    el.attr("min", rule["value"]);
                    if (!$P.isnullorempty(rule["message"])) {
                        el.attr("min_msg", rule["message"]);
                    }
                } else if (rule["rule"] == "max") {
                    el.attr("max", rule["value"]);
                    if (!$P.isnullorempty(rule["message"])) {
                        el.attr("max_msg", rule["message"]);
                    }
                } else if (rule["rule"] == "length") {
                    el.attr("rangelength", "[" + rule["min"] + "," + rule["max"] + "]");
                    if (!$P.isnullorempty(rule["message"])) {
                        el.attr("rangelength_msg", rule["message"]);
                    }
                } else if (rule["rule"] == "digits") {
                    if (rule["fraction"] == "0") {
                        el.attr("digits", true);
                    } else {
                        el.attr("jdigits", "[" + rule["fraction"] * 1 + "," + $P.getNumber(rule["integer"]) * -1 + "," + $P.getNumber(rule["integer"]) + "]");

                        el.attr("jdigits_msg", "数字的值超出了范围(只允许在" + rule["integer"] + "位整数和" + rule["fraction"] + "位小数范围内)");
                    }

                    if (!$P.isnullorempty(rule["message"])) {
                        el.attr("digits_msg", rule["message"]);
                    }
                } else if (rule["rule"] == "range") {
                    el.attr("range", "[" + rule["min"] + "," + rule["max"] + "]");
                    if (!$P.isnullorempty(rule["message"])) {
                        el.attr("range_msg", rule["message"]);
                    }
                } else if (rule["rule"] == "pattern") {
                    //todo 正则
                }
            }

        } catch (e) {
            console.log(e);
        }
        el = null;
    },
    /**处理后台返回的表单元素错误*/
    processFormError: function (formEl, errors) {
        if (formEl == undefined || errors == null || errors == undefined || errors.length == undefined || errors.length == 0) {
            return;
        }
        var errMsgAy = new Array();
        for (var i = 0; i < errors.length; i++) {
            var error = errors[i];
            var el = formEl.find("#" + error["fieldName"]);
            if (el.length == 0) {
                var label = formEl.find("label[for=" + error["fieldName"] + "]");
                if (label.length > 0) {
                    errMsgAy.push($P.gv(label.text()) + error["errorMessage"]);
                } else {
                    errMsgAy.push(error["errorMessage"]);
                }
                continue;
            }

            el.attr("title", error["errorMessage"]);
            el.addClass("error");

            if (!(el.attr("initTip") == "true" || el.attr("data-toggle") == 'tooltip')) {
                el.tooltip();
                el.attr("initTip", true);
            }
        }

        if (errMsgAy.length > 0) {
            layer.alert(errMsgAy.join("<br/>"));
        }

    },
    /*下拉框赋值*/
    setSuggestValue: function (obj, val, callFun, text) {
        var el = obj;
        if ((typeof obj) == "string") {
            el = $("#" + obj);
        }
        if (text != undefined) {
            el.attr("data-id", val).val(text);
            return;
        }

        if (el.data("bsSuggest") == undefined || el.data("bsSuggest").options == undefined || el.data("bsSuggest").options.data == undefined) {
            return
        }
        var idField = el.data("bsSuggest").options["idField"];
        var keyField = el.data("bsSuggest").options["keyField"];
        // var dataAy = el.data("bsSuggest").options.data.value;
        var isProxy = el.data("bsSuggest").options['isProxy'];
        var name = el.data("bsSuggest").options['name'];
        var code = el.data("bsSuggest").options['code'];
        var param = el.data("bsSuggest").options['param'];
        var dataurl = el.data("bsSuggest").options['dataurl'];
        if (isProxy && typeof(isProxy) === 'boolean' && dataurl) {
            var param = param;
            param.inputValue = val;
            param.idField = code;
            param.keyField = name;
            var result = app.callAjaxPostSync(dataurl, param);
            if (result.data && result.data.length > 0) {
                el.data("bsSuggest").options.data = {value: result.data};
            } else {
                el.data("bsSuggest").options.data = {value: []};
            }
        }
        var dataAy = el.data("bsSuggest").options.data.value;
        for (var i = 0; i < dataAy.length; i++) {
            var item = dataAy[i];
            if (item[idField] == val) {
                el.val(item[keyField]).attr("data-id", val);
                if ((typeof callFun) == 'function') {
                    // callFun.call(el, val, item);
                    callFun({id: item[idField], key: item[keyField]});
                }
                break;
            }
        }

    },
    //下拉框数据源变更
    reFreshSuggestData: function (obj, param, url) {
        var el = obj;
        if ((typeof obj) == "string") {
            el = $("#" + obj);
        }
        if (el.data("bsSuggest") == undefined || el.data("bsSuggest").options == undefined) {
            return
        }
        el.data("bsSuggest").options['param'] = param;
        el.data("bsSuggest").options['dataurl'] = url;
        var result = app.callAjaxPostSync(url, param);
        if (result.data && result.data.length > 0) {
            el.data("bsSuggest").options.data = {value: result.data};
            el.val('');
            el.attr("data-id", "");
        } else {
            el.data("bsSuggest").options.data = {value: []};
        }
    },
    /*根据字典表初始化下拉框*/
    initDropdownFromDic: function (el, pCode, config, callFun, field) {
        var param = {};
        if ((typeof pCode) == "object") {
            $.extend(param, pCode);
        } else {
            param["pcode"] = pCode;
        }
        $P.initDropdown(el, param, config, callFun, "../../../../api/BaseDictionaryController/selectByPcode", field);
    },
    /**根据远程返回的数据初始化下拉框**/
    initDropdown: function (el, param, config, callFun, url, field, defaultCheck) {
        el.attr("isdropdown", "true");
        //添加blur事件
        if (el.attr("bindBlur") != 'true') {
            el.blur(function () {
                if ($P.isnullorempty(el.val())) {
                    el.attr("data-id", "");
                    if ((typeof callFun) == "function") {
                        callFun.call(this, {id: "", key: ""});
                    }
                }
            }).attr("bindBlur", true);
        }
        if ($P.isnullorempty(config.name)) {
            config.name = config.keyField;
        }
        if ($P.isnullorempty(config.code)) {
            config.code = config.idField;
        }
        if (typeof(config.isProxy) === 'boolean' && config.isProxy) {
            if (!$P.isnullorempty(config.defaultValue)) {
                param.inputValue = config.defaultValue;
            }
            param.idField = config.code;
            param.keyField = config.name;
        }

        /*本地数据*/
        if ((typeof url) != 'string') {
            //处理是否能选空
            if (config.bEmpty == true && !$P.isnullorempty(config.idField) && !$P.isnullorempty(config.keyField)) {
                var firstData = {};
                firstData[config.idField] = "";
                firstData[config.keyField] = $P.gv(config.emptyText, "");
                result.data.splice(0, 0, firstData);
            }

            var bsSuggest = el.bsSuggest($.extend({
                data: {
                    'value': url
                }
            }, config)).on('onSetSelectValue', function (e, keyword) {
                if ((typeof callFun) == "function") {
                    callFun.call(this, keyword, e);
                }
            });

            //处理默认值defaultValue
            if (!$P.isnullorempty(config.defaultValue) && !$P.isnullorempty(config.idField) && !$P.isnullorempty(config.keyField)) {
                for (var i = 0; i < url.length; i++) {
                    var item = url[i];
                    if (item[config.idField] == config.defaultValue) {
                        el.val(item[config.keyField]).attr("data-id", config.defaultValue);
                        break;
                    }
                }
            }

            return;
        }

        /*远程数据*/
        app.callAjaxPost(url, param, function (result) {
                if (result.success) {
                    //处理是否能选空
                    if (config.bEmpty == true && !$P.isnullorempty(config.idField) && !$P.isnullorempty(config.keyField)) {
                        var firstData = {};
                        firstData[config.idField] = "";
                        firstData[config.keyField] = $P.gv(config.emptyText, "");
                        result.data.splice(0, 0, firstData);
                    }
                    if (typeof(config.isProxy) === 'boolean' && config.isProxy) {
                        config.dataurl = url;
                        config.param = param;
                    }
                    var bsSuggest = el.bsSuggest($.extend({
                        data: {
                            'value': result.data
                        }
                    }, config)).on('onSetSelectValue', function (e, keyword) {
                        if ((typeof callFun) == "function") {
                            callFun.call(this, keyword, e);
                        }
                    });

                    //处理默认值defaultValue
                    if (!$P.isnullorempty(config.defaultValue) && !$P.isnullorempty(config.idField) && !$P.isnullorempty(config.keyField)) {
                        for (var i = 0; i < result.data.length; i++) {
                            var item = result.data[i];
                            if (item[config.idField] == config.defaultValue) {
                                el.val(item[config.keyField]).attr("data-id", config.defaultValue);
                                // if ((typeof callFun) == "function") {
                                //     callFun({
                                //         'id': item[config.idField],
                                //         'key': item[config.keyField]
                                //     });
                                // }
                                break;
                            }
                        }
                    } else if (!$P.isnullorempty(field)) {
                        if (field && typeof(field) === 'string' && result.data && result.data.length === 1) {
                            $P.setSuggestValue(field, result.data[0][config.idField]);
                            if ((typeof callFun) == "function") {
                                callFun({
                                    'id': result.data[0][config.idField],
                                    'key': result.data[0][config.keyField]
                                });
                            }
                        }
                        if (field && typeof(field) === 'object' && result.data && result.data.length > 0 && field.isDefault) {
                            if (result.data.length === 1 || result.data[0][field.isDefault] == '1') {
                                $P.setSuggestValue(field.name, result.data[0][config.idField]);
                                if ((typeof callFun) == "function") {
                                    callFun({
                                        'id': result.data[0][config.idField],
                                        'key': result.data[0][config.keyField]
                                    });
                                }
                            }
                        }
                        if (field && typeof(field) == 'number' && field > 0 && result.data && result.data.length >= field) {
                            var item = result.data[field - 1]
                            el.val(item[config.keyField]).attr("data-id", item[config.idField]);
                            if ((typeof callFun) == "function") {
                                callFun({
                                    'id': item[config.idField],
                                    'key': item[config.keyField]
                                });
                            }
                        }
                    }
                } else {
                    var bsSuggest = el.bsSuggest($.extend({
                        data: {
                            'value': []
                        }
                    }, config)).on('onSetSelectValue', function (e, keyword) {
                        if ((typeof callFun) == "function") {
                            callFun.call(this, keyword, e);
                        }
                    });
                }
            }
        );

    },
    toThousands: function (num, dotLength) {
        if ($P.isnullorempty(num) || !$P.isnumber(num)) return num;
        var numstr = (num || 0).toString(), result = '', dot = '';
        var dotIndex = numstr.indexOf(".");
        if (dotIndex >= 0) {
            if (dotLength) {
                dot = numstr.substring(dotIndex, dotIndex + dotLength);
            } else {
                dot = numstr.substring(dotIndex, numstr.length);
            }
            numstr = numstr.substring(0, dotIndex);
        }
        while (numstr.length > 3) {
            result = ',' + numstr.slice(-3) + result;
            numstr = numstr.slice(0, numstr.length - 3);
        }
        if (numstr) {
            result = numstr + result;
        }
        return result + dot;
    },
    /**** 根据当前文本内容长度， 显示成省略号 ***/
    contentOverFlow: function (tdValue, length) {
        if (length === undefined) {
            length = 20;
        }
        var result = "";
        if (tdValue !== null && tdValue !== undefined && tdValue.length > length) {
            result = "<span title='" + tdValue + "'>" + tdValue.substring(0, length) + "...</span>"
        } else {
            result = tdValue;
        }
        return result;
    }
}

Vue.directive('amount', {
    bind: function (el, binding, vnode) {
        if (binding["name"] == "amount") {
            var elVal = $(el).attr("realvalue");
            $(el).val($P.toThousands(elVal));
        }

        $(el).data("type", "amount");

        var dataKey = "";
        var valKey = "";

        var args = $(el).attr("amount-arg").split(",");
        dataKey = args[0];
        if (args.length > 1) {
            valKey = args[1];
        } else {
            if (!$P.isnullorempty($(el).attr("valKey"))) {
                valKey = $(el).attr("valKey");
            }
            {
                valKey = $(el).attr("name");
            }
        }

        $(el).bind("change", function () {
            this.value = this.value.replace(/[^0-9.\-\\,]/g, "");
            Vue.set(vnode.context[dataKey], valKey, this.value.replace(/[^0-9.\-]/g, ""));
        });

        $(el).bind("keyup", function () {
            this.value = this.value.replace(/[^0-9.\-\\,]/g, "");
            Vue.set(vnode.context[dataKey], valKey, this.value.replace(/[^0-9.\-]/g, ""));
        });
    },
    // 当绑定元素插入到 DOM 中。
    update: function (el, binding, vnode) {
        if (binding["name"] == "amount") {
            var elVal = $(el).attr("realvalue");
            $(el).val($P.toThousands(elVal));
        }
    }
});

/**
 * 遮罩层
 *
 */
var loading = function () {
    return {
        load: null,
        show: function () {
            this.load = layer.load(2, {
                content: '正在处理，请稍候...', shade: [0.1, '#393D49'],
                success: function (layero) {
                    layero.find('.layui-layer-content').css('width', '200px');
                    layero.find('.layui-layer-content').css('padding-left', '40px');
                    layero.find('.layui-layer-content').css('padding-top', '5px');
                    layero.find('.layui-layer-content').css('font-size', '16px');
                    layero.find('.layui-layer-content').css('color', '#595b5d');
                    layero.find('.layui-layer-content').css('font-weight', 'bold');
                }
            })
            ;
        },
        close: function () {
            if (this.load != null) {
                layer.close(this.load);
            }
        }
    };
};

/**
 * 提示悬浮组件
 *
 * type:0 警告，1、成功，2、错误，3、普通信息
 *
 * message：显示的信息
 *
 */
var myAlert = function (type, message) {

    toastr.clear();

    //配置
    toastr.options = {
        closeButton: true,
        debug: false,
        progressBar: false,
        positionClass: 'toast-top-center',
        onclick: null,
        showDuration: 0,
        hideDuration: 500,
        timeOut: 2000,
        extendedTimeOut: 500,
        showEasing: 'swing',
        hideEasing: 'linear',
        showMethod: 'fadeIn',
        hideMethod: 'fadeOut',
        preventDuplicates: true
    };

    switch (type) {

        case 0://警告
            toastr['warning'](message, '警告');
            break;
        case 1://成功
            toastr['success'](message, '提示');
            break;
        case 2://错误
            toastr['error'](message, '错误');
            break;
        case 3://普通信息
            toastr['info'](message, '提示');
            break;
        default:
            toastr['info'](message, '提示');
            break;
    }
};


//自定义一个验证方法for java validate digits
$.validator.addMethod(
    "jdigits", //验证方法名称
    function (value, element, param) {//验证规则
        if (value === '') {  //updated by sun jiahu， when the value is empty, pass it.
            return true;
        } else {
            var ay;
            if ((typeof param) == "string") {
                eval("ay=" + param);
            } else {
                ay = param;
            }
            return $P.isnumber(value, ay[0] * 1, ay[1], ay[2]);
        }

    },
    "输入的值超出了范围"
);

Date.prototype.format = function (format) {
    if (format == undefined || format == '')
        format = 'yyyy/MM/dd';
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(),    //day
        "h+": this.getHours(),   //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds() //millisecond
    }

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
    return format;
}

/*** 自动截取过长的文本内容,显示成省略号 ****/
function tdOverFlow(tableId, length) {
    $("#" + tableId + " tr td").each(function (i) {
        //获取td当前对象的文本,如果长度大于length;  
        if ($(this).has("a").length == 0 && $(this).text().length > length) {
            //给td设置title属性,并且设置td的完整值.给title属性.  
            $(this).attr("title", $(this).text());
            //获取td的值,进行截取。赋值给text变量保存.  
            var text = $(this).text().substring(0, length) + "...";
            //重新为td赋值;  
            $(this).text(text);
        }
    });
}

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}



